﻿using System;
using System.Collections.Generic;
using System.Linq;
using Ninject.Core.Parameters;
using TestBat.IModels.Domain;
using TestBat.IModels.Models;
using TestBat.IModels.Repositories;
using TestBat.Models.Attributes;
using TestBat.ServiceLocator;

namespace TestBat.Models.Models
{
    //[PersistenceConversational(MethodsIncludeMode = MethodsIncludeMode.Implicit)]
    public class TaskModel : Model, ITaskModel
    {
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="essayTaskRepository">the repository to be used</param>
        public TaskModel(ITaskRepository taskRepository)
        {
            this.taskRepository = taskRepository;
        }

        /// <summary>
        /// get a task by ID
        /// </summary>
        /// <param name="taskID">the ID</param>
        /// <returns>the found task or null, if none is found</returns>
        [Conversation]
        public ITask GetByID(Guid taskID)
        {
            return taskRepository.GetByID(taskID);
        }

        /// <summary>
        /// save/persist a task
        /// </summary>
        /// <param name="task">the task to save</param>
        [Conversation(ConversationEndMode.CommitAndContinue)]
        public void Save(ITask task)
        {
            Validate(task);

            taskRepository.MakePersistent(task);
        }

        /// <summary>
        /// delete a task
        /// </summary>
        /// <param name="task">the task to delete</param>
        [Conversation(ConversationEndMode.CommitAndContinue)]
        public void Delete(ITask task)
        {
            taskRepository.MakeTransient(task);
        }

        /// <summary>
        /// revert an task back to database-state
        /// </summary>
        /// <param name="task">the task</param>
        [Conversation]
        public void Revert(ITask task)
        {
            taskRepository.Refresh(task);
        }

        [Conversation]
        public IList<IChoice> GetChoices(IChoiceTask task)
        {
            return (from c in task.Choices select c).ToList<IChoice>();
        }

        [Conversation]
        public void AddChoice(IChoiceTask task)
        {
            IChoice c = DefaultServiceLocator.Get<IChoice>(With.Parameters.Variable("manual", true));

            c.Task = task;

            taskRepository.MakePersistent(task);
        }

        [Conversation]
        public void RemoveChoice(IChoice choice)
        {
            IChoiceTask task = choice.Task;

            choice.Task = null;

            taskRepository.MakePersistent(task);
        }

        /// <summary>
        /// the actual repository
        /// </summary>
        protected readonly ITaskRepository taskRepository;
    }
}
